<?php

namespace app\index\controller;

use app\BaseController;
use think\facade\View;

class RedisWay extends BaseController
{
    /**
     * redis列表
     */
    public function doSearch()
    {
        // 开启redis缓存
        if ($this->request->isPost()) {
            $redis = new \Redis();
            $rs = $redis->connect('127.0.0.1', 6379);
            if ($rs === false) {
                echo 'redis conn failed';
                exit;
            }
            $keyword = $this->request->param('keyword') ?: '';
            $user_id = 1;
            $redis_key = 'search-' . $user_id;
            if (!empty($keyword)) {
                if ($redis->lLen($redis_key) >= 4) {
                    $redis->rPop($redis_key);
                }
                $redis->lPush($redis_key, $keyword);
            }
            // 取出列表值4个
            $data = $redis->lRange($redis_key, 0, 3);
            echo "<form action=\"\" method=\"post\">
        搜索内容<input type=\"text\" name=\"keyword\"><br />
        <button type=\"submit\">搜索</button>
    </form><div>";
            foreach ($data as $k => $v) {
                echo "<span>" . $v . "</span><br/>";
            }
            echo "</div>";
        } else {

            return View::fetch();
        }
    }

    /**
     * redis字符串
     */
    public function setPage()
    {
        // 开启redis缓存
        $url = 'https://www.runoob.com/redis/hashes-hget.html';
        $context = stream_context_create([
            "ssl" => [
                "verify_peer" => false,
                "verify_peer_name" => false,
                "allow_self_signed" => true
            ]
        ]);
        $html = file_get_contents($url, false, $context);
        // 字符串
        cache('page', $html);
        dump(cache('page'));
    }
}
